﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using S2_2.Models;
using S2_2.Services;
using S2_2.Services.Models;

namespace S2._2.Controllers
{
    [Authorize]
    [ApiController]
    public class PersonalController : ControllerBase
    {
        private readonly UserService _userService;

        public PersonalController(UserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 获取当前用户个人资料
        /// </summary>
        [HttpGet]
        //[AllowAnonymous] // 允许匿名访问
        [Route("api/profile")]
        public AppResult<ProfileOutput> Profile()
        {
            var email = User.Identity.Name;
            var profile = _userService.GetProfile(email);
            return profile;
        }

        /// <summary>
        /// 上传用户图片
        /// </summary>
        [HttpPost]
        [Route("api/uploadPicture")]
        public AppResult<string> UploadPicture(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new AppResult<string>(false, "文件不能为空");
            }

            try
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", fileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                return new AppResult<string>(true, "文件上传成功");
            }
            catch (Exception ex)
            {
                return new AppResult<string>(false, $"文件上传失败: {ex.Message}");
            }
        }
    }
}
